package v1

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Rsp struct {
	Code    int       `json:"code"`
	Message string    `json:"message,omitempty"`
	Reason  string    `json:"reason,omitempty"`
	Data    any       `json:"data,omitempty"`
	Cache   bool      `json:"cache"`
	Trace   string    `json:"trace"`
	Page    *PageData `json:"page,omitempty"`
}

type RspChain struct {
	rsp Rsp
	ctx *gin.Context
}

func NewRsp(ctx *gin.Context) *RspChain {
	return &RspChain{
		ctx: ctx,
		rsp: Rsp{
			Code:  0,
			Cache: false,
		},
	}
}

func (r *RspChain) WithMsg(msg RspMsg) *RspChain {
	r.rsp.Code = msg.code
	r.rsp.Message = msg.message
	return r
}
func (r *RspChain) WithReason(err error) *RspChain {
	if err == nil {
		return r
	}
	if msg, ok := err.(RspMsg); ok {
		r.WithMsg(msg)
		return r
	}
	if r.rsp.Code == 0 {
		r.rsp.Code = ErrInternalServerError.code
		r.rsp.Message = ErrInternalServerError.message
	}
	r.rsp.Reason = err.Error()
	return r
}

func (r *RspChain) WithData(data any) *RspChain {
	r.rsp.Data = data
	return r
}

func (r *RspChain) WithPageData(page *PageData, data any) *RspChain {
	r.rsp.Data = data
	r.rsp.Page = page
	return r
}

func (r *RspChain) WithCache(cache bool) *RspChain {
	r.rsp.Cache = cache
	return r
}

func (r *RspChain) Send() {
	if r.ctx.IsAborted() {
		return
	}
	trace := r.ctx.GetString("trace")
	if trace == "" {
		trace = "unknown" // 设置默认值，增强调试友好性
	}
	r.rsp.Trace = trace
	r.ctx.JSON(http.StatusOK, r.rsp)
}
